# -*- coding: utf-8 -*-
__author__ = 'lieber'
import json
import unittest


class MyAssert(unittest.TestCase):

    def my_assert(self, res, assert_msg):
        status_code = res.status_code
        self.assertEqual(status_code, 200, '【响应状态码断言】实际值：' + str(status_code) + '，期望值：200')
        if assert_msg is None or assert_msg == '':
            return
        flag = 0
        try:
            try:
                res_json = res.json()
                assert_msg = json.loads(assert_msg)
                self.compare_dict(assert_msg, res_json)
            except ValueError:
                flag = 1

            if flag == 1:
                try:
                    self.assertIn(assert_msg, str(res.text), '不包含，断言不通过')
                except ValueError:
                    flag = 2
        except ValueError:
            print('断言失败，请检查')
        finally:
            # print("【request请求的response内容为：%s】" % res.text)
            pass

    def compare_dict(self, src_data, dst_data):
        '''
        原文：https://blog.csdn.net/qq_37023538/article/details/54379591?utm_source=copy
        :param src_data:
        :param dst_data:
        :return:
        '''
        assert type(src_data) == type(dst_data),"type: '{}' != '{}'".format(type(src_data), type(dst_data))
        if isinstance(src_data,dict):
            for key in src_data:
                #assert dst_data.has_key(key)
                assert  key in dst_data
                self.compare_dict(src_data[key],dst_data[key])
        elif isinstance(src_data,list):
            for src_list, dst_list in zip(sorted(src_data), sorted(dst_data)):
                self.compare_dict(src_list, dst_list)
        else:
            assert src_data == dst_data, "value '{}' != '{}'".format(src_data, dst_data)

    def assert_in(self, response, assert_msg):
        if assert_msg in response:
            return 'success'
        else:
            return 'fail'

